<template>
  <div class="character-create-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="flex items-center gap-4">
        <n-button
          text
          class="text-gray-600 hover:text-gray-900"
          @click="$router.back()"
        >
          <template #icon>
            <svg
              class="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M15 19l-7-7 7-7"
              ></path>
            </svg>
          </template>
          返回
        </n-button>
        <div>
          <h1 class="text-2xl font-bold text-gray-900">创建AI角色</h1>
          <p class="text-gray-600 mt-1">描述故事背景，AI将为您生成独特的角色</p>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <n-alert
      v-if="error"
      type="error"
      :title="error"
      closable
      class="mb-6"
      @close="clearError"
    />

    <!-- 创建表单 -->
    <div class="create-form">
      <n-card title="故事背景设定" class="mb-6">
        <n-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-placement="top"
        >
          <n-form-item label="故事背景" path="background">
            <n-input
              v-model:value="formData.background"
              type="textarea"
              placeholder="请详细描述故事的背景设定，包括世界观、时代背景、环境等信息。例如：这是一个魔法与科技并存的现代都市，魔法师们隐藏在普通人中间..."
              :rows="8"
              :maxlength="2000"
              show-count
              clearable
            />
          </n-form-item>

          <div class="form-actions">
            <n-button
              type="primary"
              size="large"
              :loading="loading"
              :disabled="!formData.background.trim()"
              @click="generateCharacter"
            >
              <template #icon>
                <svg
                  class="w-5 h-5"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M13 10V3L4 14h7v7l9-11h-7z"
                  ></path>
                </svg>
              </template>
              生成角色
            </n-button>
          </div>
        </n-form>
      </n-card>

      <!-- 生成的角色预览 -->
      <n-card
        v-if="generatedCharacter"
        title="生成的角色"
        class="character-preview"
      >
        <div class="character-details">
          <div class="character-header">
            <div class="character-avatar">
              <div class="avatar-placeholder">
                {{ generatedCharacter.name.charAt(0) }}
              </div>
            </div>
            <div class="character-basic-info">
              <h3 class="character-name">{{ generatedCharacter.name }}</h3>
              <div class="character-personality">
                <n-tag
                  v-for="trait in generatedCharacter.personality"
                  :key="trait"
                  type="info"
                  class="mr-2 mb-2"
                >
                  {{ trait }}
                </n-tag>
              </div>
            </div>
          </div>

          <div class="character-attributes">
            <div class="attribute-item">
              <h4 class="attribute-label">说话风格</h4>
              <p class="attribute-value">
                {{ generatedCharacter.speakingStyle }}
              </p>
            </div>

            <div class="attribute-item">
              <h4 class="attribute-label">知识领域</h4>
              <p class="attribute-value">
                {{ generatedCharacter.knowledgeBase }}
              </p>
            </div>

            <div class="attribute-item">
              <h4 class="attribute-label">故事背景</h4>
              <p class="attribute-value">{{ generatedCharacter.background }}</p>
            </div>
          </div>

          <div class="preview-actions">
            <n-button
              type="primary"
              size="large"
              @click="startChatWithCharacter"
            >
              开始对话
            </n-button>
            <n-button
              size="large"
              :loading="loading"
              @click="regenerateCharacter"
            >
              重新生成
            </n-button>
            <n-button size="large" @click="goToCharacterList">
              返回列表
            </n-button>
          </div>
        </div>
      </n-card>

      <!-- 示例背景 -->
      <n-card v-if="!generatedCharacter" title="示例背景" class="examples">
        <div class="example-list">
          <div
            v-for="example in examples"
            :key="example.title"
            class="example-item"
            @click="useExample(example.content)"
          >
            <h4 class="example-title">{{ example.title }}</h4>
            <p class="example-content">{{ example.content }}</p>
          </div>
        </div>
      </n-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import {
  NButton,
  NAlert,
  NCard,
  NForm,
  NFormItem,
  NInput,
  NTag,
  useMessage,
} from 'naive-ui';
import { useRoleplayStore } from '@/stores/roleplay';
import type { Character } from '@/types/roleplay';

const router = useRouter();
const message = useMessage();
const store = useRoleplayStore();

// 从store中获取状态和方法
const {
  loading,
  error,
  generateCharacter: storeGenerateCharacter,
  createConversation,
  clearError,
} = store;

// 表单数据
const formData = reactive({
  background: '',
});

// 表单验证规则
const formRules = {
  background: [
    { required: true, message: '请输入故事背景', trigger: 'blur' },
    { min: 50, message: '故事背景至少需要50个字符', trigger: 'blur' },
  ],
};

// 生成的角色
const generatedCharacter = ref<Character | null>(null);

// 示例背景
const examples = [
  {
    title: '魔法学院',
    content:
      '这是一个现代魔法学院，学生们在这里学习各种魔法技能。学院位于一座古老的城堡中，周围环绕着神秘的森林。每个学生都有自己的魔法天赋，有的擅长元素魔法，有的精通占卜术。',
  },
  {
    title: '赛博朋克都市',
    content:
      '2077年的新东京，霓虹灯闪烁的街道上，人类与机器人共存。大型企业控制着城市的每一个角落，而黑客们在虚拟网络中寻找着自由。这里科技高度发达，但社会分化严重。',
  },
  {
    title: '古代仙侠世界',
    content:
      '这是一个修仙者遍布的古代世界，各大门派林立，修炼者追求长生不老。这里有飞剑、法宝、丹药，还有各种神兽和妖怪。正邪两道时常发生冲突，江湖风云变幻莫测。',
  },
];

// 生成角色
const generateCharacter = async () => {
  try {
    const character = await storeGenerateCharacter(formData.background);
    generatedCharacter.value = character;
    message.success('角色生成成功！');
  } catch (error) {
    console.error('生成角色失败:', error);
  }
};

// 重新生成角色
const regenerateCharacter = async () => {
  generatedCharacter.value = null;
  await generateCharacter();
};

// 使用示例
const useExample = (content: string) => {
  formData.background = content;
};

// 开始与角色对话
const startChatWithCharacter = async () => {
  if (!generatedCharacter.value) return;

  try {
    // 创建新对话
    const conversation = await createConversation(generatedCharacter.value.id);

    // 跳转到对话页面
    router.push({
      name: 'Chat',
      params: {
        characterId: generatedCharacter.value.id,
        conversationId: conversation.id,
      },
    });
  } catch (error) {
    console.error('开始对话失败:', error);
  }
};

// 返回角色列表
const goToCharacterList = () => {
  router.push({ name: 'CharacterList' });
};
</script>

<style scoped>
@reference "@/styles/app.css";

.character-create-page {
  @apply max-w-4xl mx-auto px-4 py-6;
}

.page-header {
  @apply mb-8;
}

.form-actions {
  @apply flex justify-center mt-6;
}

.character-preview {
  @apply border-2 border-green-200 bg-green-50;
}

.character-details {
  @apply space-y-6;
}

.character-header {
  @apply flex items-start gap-4;
}

.character-avatar {
  @apply flex-shrink-0;
}

.avatar-placeholder {
  @apply w-16 h-16 bg-blue-500 text-white rounded-full flex items-center justify-center text-xl font-bold;
}

.character-basic-info {
  @apply flex-1;
}

.character-name {
  @apply text-xl font-bold text-gray-900 mb-3;
}

.character-personality {
  @apply flex flex-wrap;
}

.character-attributes {
  @apply space-y-4;
}

.attribute-item {
  @apply bg-white p-4 rounded-lg border border-gray-200;
}

.attribute-label {
  @apply text-sm font-medium text-gray-700 mb-2;
}

.attribute-value {
  @apply text-gray-900;
}

.preview-actions {
  @apply flex gap-3 justify-center;
}

.examples {
  @apply mt-6;
}

.example-list {
  @apply space-y-4;
}

.example-item {
  @apply p-4 border border-gray-200 rounded-lg cursor-pointer hover:border-blue-300 hover:bg-blue-50 transition-colors;
}

.example-title {
  @apply font-medium text-gray-900 mb-2;
}

.example-content {
  @apply text-sm text-gray-600;
}
</style>
